package com.juli.v2xdemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import com.juli.v2xdemo.animator.AnimaTools;
import com.juli.v2xdemo.entity.Bullet;
import com.juli.v2xdemo.entity.Bulleter;
import com.juli.v2xdemo.entity.Bulletsan;
import com.juli.v2xdemo.entity.Car;
import com.juli.v2xdemo.entity.Enemy;
import com.juli.v2xdemo.entity.Enemy2;
import com.juli.v2xdemo.entity.OtherCar;
import com.juli.v2xdemo.listener.AddBoomListener;
import com.juli.v2xdemo.listener.AddBulletListener;
import com.juli.v2xdemo.listener.AddBulleterListener;
import com.juli.v2xdemo.listener.AddBulletsanListener;
import com.juli.v2xdemo.listener.AddEnemyListener;
import com.juli.v2xdemo.listener.AddEnemyListener2;
import com.juli.v2xdemo.util.GPSutils;

/**
 * 场景控制类
 *
 * @author Administrator
 */
public class PlaneWar2 extends FrameLayout {
    private Paint paint = null;
    private final int CREATE_BULLET_DURATION = 4050;// 生产子弹间隔时间
    private final int MSG_BULLETer = 4100;// 生产子弹间隔时间
    private final int MSG_BULLETsan = 4150;// 生产子弹间隔时间
    private final int MSG_ENEMY = 1;
    private final int MSG_BULLET = 2;



    public PlaneWar2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public PlaneWar2(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PlaneWar2(Context context) {
        super(context);
        init();
    }

    private void init() {

    }

    public Car getmCarData() {
        return mCarData;
    }

    public void setmCarData(Car mCarData) {
        this.mCarData = mCarData;
    }


    private Car mCarData;

    public OtherCar getOtherCar() {
        return otherCar;
    }

    public void setOtherCar(OtherCar otherCar) {
        this.otherCar = otherCar;
    }

    private OtherCar otherCar;


    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case MSG_ENEMY:
                    generateEnemy();
                    break;
                case MSG_BULLET:
                    Log.e("zzzzz", "触发了1111111111111111"+GPSutils.chu);


//                        Log.e("zzzzz", "触发了1111111111111111");
                        generateBullet();


                    break;
                case MSG_BULLETer:
                        generateBulleter();
                    break;
                case MSG_BULLETsan:
                        generateBulletsan();




                    break;
            }
        };
    };





    /**
     * 制造敌人，每隔一段时间制造一个
     */
    private void generateEnemy() {
        Enemy2 enemy = new Enemy2(getContext());
        enemy.setPlaneWar(this);
        enemy.getViewTreeObserver().addOnGlobalLayoutListener(
                new AddEnemyListener2(enemy));
        addView(enemy);


    }
    Object tag;
    /**
     * 生产子弹
     */
    private void generateBullet() {
        if (GPSutils.chu) {
//                        Log.e("zzzzz", "触发了1111111111111111");
            Bullet bullet = new Bullet(getContext());
            bullet.setCarData(mCarData);
            bullet.getViewTreeObserver().addOnGlobalLayoutListener(
                    new AddBulletListener(bullet));
            addView(bullet);
            tag = bullet.getTag();
        } else {

        }


        // 循环制造子弹
        handler.sendEmptyMessageDelayed(MSG_BULLET, CREATE_BULLET_DURATION);
    }

    private void generateBulleter() {
        if (GPSutils.chu) {
        Bulleter bullet = new Bulleter(getContext());
        bullet.setCar(mCarData);
        bullet.getViewTreeObserver().addOnGlobalLayoutListener(
                new AddBulleterListener(bullet));
        addView(bullet);
        }
        // 循环制造子弹
        handler.sendEmptyMessageDelayed(MSG_BULLETer, CREATE_BULLET_DURATION);
    }
    private void generateBulletsan() {
        Bulletsan bullet = new Bulletsan(getContext());
        bullet.setCarData(mCarData);
        bullet.getViewTreeObserver().addOnGlobalLayoutListener(
                new AddBulletsanListener(bullet));
        addView(bullet);
        // 循环制造子弹
        handler.sendEmptyMessageDelayed(MSG_BULLETsan, CREATE_BULLET_DURATION+GPSutils.xianshi);
    }

public void start(){
    generateBullet();
    generateBulleter();
//    generateBulletsan();
}






    /**
     * 重新开始游戏
     */
    public void clearAll() {
//        handler.removeMessages(MSG_ENEMY);
//        handler.removeMessages(MSG_BULLET);
        // 清除所有游戏实体
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = getChildAt(i);
            if (view instanceof Enemy) {
                Enemy enemy = (Enemy) view;
                enemy.stopAnimation();
            } else if (view instanceof Bullet) {
                Bullet bullet = (Bullet) view;
                bullet.stopAnimation();
            }
        }

         removeAllViews();


    }

    /**
     * 引爆敌人，此处不能用WindowManager实现，因为同时可能引爆多个
     *
     * @param translationY
     * @param translationX
     * @param
     */
    public void boomEnemy(float translationX, float translationY) {
        // 创建用于临时爆炸的敌人
        View v = new View(getContext());
        Drawable drawable = getResources().getDrawable(R.drawable.enemy_boom);
        v.setLayoutParams(new LayoutParams(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight()));
        v.setBackgroundDrawable(drawable);
        v.setTranslationX(translationX);
        v.setTranslationY(translationY);

        v.getViewTreeObserver().addOnGlobalLayoutListener(
                new AddBoomListener(v));
        addView(v);
    }

    /**
     * 引爆英雄
     */
    public void boomHero() {
        // 创建用于临时爆炸的英雄
        View v = new View(getContext());

        Drawable drawable = getResources().getDrawable(R.drawable.hero_boom);
        v.setLayoutParams(new LayoutParams(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight()));
        v.setBackgroundDrawable(drawable);
        v.setTranslationX(mCarData.getTranslationX());
        v.setTranslationY(mCarData.getTranslationY());

        v.getViewTreeObserver().addOnGlobalLayoutListener(
                new AddBoomListener(v));
        addView(v);
    }

    /**
     * 移除子弹
     */
    public void removeBullet() {
//         handler.removeMessages(MSG_BULLET);
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = getChildAt(i);
            if (view instanceof Bullet && view.getTag()==tag) {
                Bullet bullet = (Bullet) view;
                bullet.stopAnimation();
                removeView(bullet);
            }
        }
    }

    public void hideHero() {
        mCarData.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
//        canvas.drawText(String.format(str, score), 1, textHeight + 1, paint);
    }

    public int getTextHeight(String text) {
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return bounds.height();
    }



// ===================================================
    /**
     * 移动英雄到某个点
     */
    public void moveHeroTo(float x, float y) {
        // 计算translation坐标和场景相对坐标的偏移量
        float xOffset = x - mCarData.getTranslationX() - mCarData.getWidth() / 2;
        float yOffset = y - mCarData.getTranslationY() - mCarData.getHeight() / 2;
        moveHeroBy(xOffset, yOffset );

    }

    /**
     * 移动英雄
     *
     * @param xOffset
     * @param yOffset
     */
    private void moveHeroBy(float xOffset, float yOffset ) {
        float newTranslationX = mCarData.getTranslationX() + xOffset;
        float newTranslationY = mCarData.getTranslationY() + yOffset;
        //变道-偏移角度
        rotationView(xOffset,mCarData);

        // 控制英雄的四边不能超出场景范围
        if (newTranslationX < 0)
            newTranslationX = 0;
        if (newTranslationX > (getWidth() - mCarData.getWidth())) {
            newTranslationX = getWidth() - mCarData.getWidth();
        }


        if (newTranslationY < 0)
            newTranslationY = 0;
        if (newTranslationY > (getHeight() - mCarData.getHeight())) {
            newTranslationY = getHeight() - mCarData.getHeight();
        }

//        Log.e("测试", "newTranslationX=" + newTranslationX);
        mCarData.setTranslationX(newTranslationX);
        mCarData.setTranslationY(newTranslationY);


    }
//============================================
    /**
     * 移动英雄到某个点
     */
    public void moveHeroToOther(float x, float y) {
        // 计算translation坐标和场景相对坐标的偏移量
        float xOffset = x - otherCar.getTranslationX() - otherCar.getWidth() / 2;
        float yOffset = y - otherCar.getTranslationY() - otherCar.getHeight() / 2;
        moveHeroByotherCar(xOffset, yOffset );
    }

    /**
     * 移动英雄
     *
     * @param xOffset
     * @param yOffset
     */
    public void moveHeroByotherCar(float xOffset, float yOffset ) {
        float newTranslationX = otherCar.getTranslationX() + xOffset;
        float newTranslationY = otherCar.getTranslationY() + yOffset;

        // 控制英雄的四边不能超出场景范围
        if (newTranslationX < 0)
            newTranslationX = 0;
        if (newTranslationX > (getWidth() - otherCar.getWidth())) {
            newTranslationX = getWidth() - otherCar.getWidth();
        }


        if (newTranslationY < 0)
            newTranslationY = 0;
        if (newTranslationY > (getHeight() - otherCar.getHeight())) {
            newTranslationY = getHeight() - otherCar.getHeight();
        }
        //变道-偏移角度
        rotationView(xOffset,otherCar);
//        Log.e("测试", "newTranslationX=" + newTranslationX);
        otherCar.setTranslationX(newTranslationX);
        otherCar.setTranslationY(newTranslationY);
        otherCar.setVisibility(VISIBLE);
    }

    /**
     * 变道-偏移角度
     * @param xOffset
     * @param view
     */
    private void rotationView(float xOffset,View view){

        if(xOffset!=0){
            if(xOffset>0){
                AnimaTools.viewRotation(view,0F,30F,500);
                AnimaTools.viewRotation(view,30F,0F,500);
            }else{
                AnimaTools.viewRotation(view,0F,-30F,500);
                AnimaTools.viewRotation(view,-30F,0F,500);
            }
    }
    }
}
